import { useState, useEffect } from 'react';
import { Checkbox, Empty, Form, Input, Button, Divider, message, Popconfirm } from "antd";
import { findIndex, cloneDeep, find, forEach } from "lodash";
import IconFont from "@/components/IconFont";
import { CloseOutlined } from "@ant-design/icons";
import CommonLoading from "@/components/CommonLoading"
import CommonModal from '@/components/CommonModal';
import NamedAddressModal from './NamedAddressModal';
import { getAllArea } from "@/services/common";
import { getQuickSearchList, delQuickSearchOp } from "./services";
import styles from "./index.module.less";

export default ({ page = 'common-address-search', allData = [], selectedList = [], handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  const [open, setOpen] = useState(false);

  //省市区信息
  const [data, setData] = useState(allData);
  //当前展示的省id
  const [provinceId, setProvinceId] = useState(undefined);
  //当前展示的市id
  const [cityId, setCityId] = useState(undefined);
  //添加常用地址命名弹窗
  const [addVisible, setAddVisible] = useState(false);
  //选择的数据
  const [selectData, setSelectData] = useState(cloneDeep(selectedList));
  //常用地址
  const [commonAddressList, setCommonAddressList] = useState([]);

  const [loading, setLoading] = useState(false);

  const [keyword, setKeyword] = useState('');

  useEffect(() => {
    setOpen(true);
    getCommonAddressList();
    if (!allData?.length) {//该弹窗可单独/直接引用使用，触发请求地址源数据
      getAreaData();
    }
    const temp = selectData?.[0] || allData?.[0];
    if (temp) {
      setProvinceId(temp?.id);
      setCityId(temp?.childs?.[0]?.id);
    }
  }, [])

  //获取省市区地址信息
  const getAreaData = async () => {
    const { data, success } = await getAllArea();
    if (success) {
      setData(data);
    }
  };

  //获取常用地址列表
  const getCommonAddressList = async () => {
    setLoading(true);
    const { success, data = [] } = await getQuickSearchList({
      page,
      current: 1,
      size: 100
    });
    if (success && data?.length) {
      const arr = [];
      data.forEach(item => {
        arr.push({
          ...item,
          delOpen: false
        });
      });
      setCommonAddressList(arr);
    }
    setLoading(false);
  };

  //选择省份
  const handleSelectProvince = (e, id) => {
    if (id > 100) {
      message.warning("暂不支持该区域");
      return;
    }
    let checked = e.target.checked;
    if (checked) {
      //全选市
      const obj = find(data, ["id", id]);
      const arr = cloneDeep(selectData);
      const index = findIndex(arr, ["id", id]);
      if (index > -1) {
        arr[index] = obj;
      } else {
        arr.push(obj);
      }
      setSelectData(arr);
      handleClickProvince(id);
    } else {
      const arr = cloneDeep(selectData);
      const index = findIndex(arr, ["id", id]);
      arr.splice(index, 1);
      setSelectData(arr);
      handleClickProvince(id);
    }
  };
  //选择市
  const handleSelectCity = (e, id) => {
    let checked = e.target.checked;
    if (checked) {
      //全选区
      //查询到省
      const obj = find(data, ["id", provinceId]);
      //查询到市
      const obj1 = find(obj.childs, ["id", id]);

      const index1 = findIndex(selectData, ["id", provinceId]);
      if (index1 > -1) {
        //如果已选列表包含当前省
        const index2 = findIndex(selectData[index1].childs, ["id", id]);
        const arr = cloneDeep(selectData);
        if (index2 > -1) {
          //如果已选包含当前市
          arr[index1].childs[index2] = obj1;
        } else {
          arr[index1].childs.push(obj1);
        }
        setSelectData(arr);
      } else {
        const arr = cloneDeep(selectData);
        const arr1 = [];
        arr1.push(obj1);
        const obj = {
          id: provinceId,
          name: find(data, ["id", provinceId]).name,
          childs: arr1
        };
        arr.push(obj);
        setSelectData(arr);
      }
    } else {
      //取消全选
      const arr = cloneDeep(selectData);
      const index1 = findIndex(selectData, ["id", provinceId]);
      const index2 = findIndex(selectData[index1].childs, ["id", id]);
      arr[index1].childs.splice(index2, 1);
      setSelectData(arr);
    }
    handleClickCity(id);
  };
  //选择区
  const handleSelectArea = (e, id) => {
    let checked = e.target.checked;
    if (checked) {
      //选择
      const index = findIndex(selectData, ["id", provinceId]);
      if (index > -1) {
        //已选列表包含当前省
        const index1 = findIndex(selectData[index].childs, ["id", cityId]);
        if (index1 > -1) {
          //已选列表包含当前市
          const obj = {
            id: id
          };
          const arr = cloneDeep(selectData);
          arr[index].childs[index1].childs.push(obj);
          setSelectData(arr);
        } else {
          const arr = [];
          arr.push({ id: id });
          const obj = {
            id: cityId,
            childs: arr
          };
          const list = cloneDeep(selectData);
          list[index].childs.push(obj);
          setSelectData(list);
        }
      } else {
        const arr = [];
        arr.push({ id });
        const obj = {
          id: cityId,
          childs: arr
        };
        const arr1 = [];
        arr1.push(obj);
        const obj1 = {
          id: provinceId,
          name: find(data, ["id", provinceId]).name,
          childs: arr1
        };
        const list = cloneDeep(selectData);
        list.push(obj1);
        setSelectData(list);
      }
    } else {
      //取消选择
      const index1 = findIndex(selectData, ["id", provinceId]);
      const index2 = findIndex(selectData[index1].childs, ["id", cityId]);
      const index3 = findIndex(selectData[index1].childs[index2].childs, ["id", id]);
      const arr = cloneDeep(selectData);
      arr[index1].childs[index2].childs.splice(index3, 1);
      setSelectData(arr);
    }
  };

  //查看省份
  const handleClickProvince = id => {
    if (id == provinceId) {
      return;
    }
    if (id > 100) {
      message.warning("暂不支持该区域");
      return;
    }
    const arr = find(data, ["id", id]).childs;
    setProvinceId(id);
    setCityId(arr[0].id);
  };
  //查看市
  const handleClickCity = id => {
    if (id == cityId) {
      return;
    }
    setCityId(id);
  };

  //判断省是否全选
  const getProvinceChecked = id => {
    const index = findIndex(selectData, ["id", id]);
    if (index > -1) {
      const arr1 = find(data, ["id", id]).childs;
      const arr2 = selectData[index].childs;
      if (arr1.length == arr2.length) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  };

  //判断市是否选择
  const getCityChecked = id => {
    const index1 = findIndex(selectData, ["id", provinceId]);
    if (index1 == -1) {
      return false;
    }
    const arr = find(selectData, ["id", provinceId]).childs;
    const index = findIndex(arr, ["id", id]);
    if (index > -1) {
      const arr1 = find(find(data, ["id", provinceId]).childs, ["id", id]).childs;
      const arr2 = find(arr, ["id", id]).childs;
      if (arr1.length == arr2.length) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  };

  //判断区是否是选择
  const getAreaChecked = id => {
    //首先判断是否是否有该省份
    const index1 = findIndex(selectData, ["id", provinceId]);
    if (index1 == -1) {
      return false;
    } else {
      //其次判断是否有该市区
      const index2 = findIndex(selectData[index1].childs, ["id", cityId]);
      if (index2 == -1) {
        return false;
      } else {
        const index3 = findIndex(selectData[index1].childs[index2].childs, ["id", id]);
        if (index3 > -1) {
          return true;
        }
        return false;
      }
    }
  };

  //显示市是否全选
  const handleSelectAllCity = id => {
    const cityData = find(selectData, ["id", provinceId]);
    if (cityData) {
      let num2 = find(cityData.childs, ["id", id]) ? find(cityData.childs, ["id", id]).childs.length : undefined;
      if (num2) {
        const cityData1 = find(data, ["id", provinceId]).childs;
        let num1 = find(cityData1, ["id", id]).childs.length;
        if (num2 < num1) {
          return true;
        }
        return false;
      }
    } else {
      return false;
    }
  };

  //渲染市列表
  const renderCity = () => {
    if (provinceId) {
      const arr = find(data, ["id", provinceId])?.childs || [];
      return (
        <div style={{ width: "260px" }}>
          {arr.map(v => (
            <span style={{ margin: "2px 8px", display: "inline-block" }} key={v.id}>
              <span className="flex-row-center">
                <Checkbox
                  indeterminate={handleSelectAllCity(v.id)}
                  checked={getCityChecked(v.id)}
                  onChange={e => handleSelectCity(e, v.id)}
                />
                <span
                  className={v.id == cityId ? styles.select : styles.normal}
                  style={{ marginLeft: 8 }}
                  key={v.id}
                  onClick={() => handleClickCity(v.id)}
                >
                  <span dangerouslySetInnerHTML={{ 
                  __html: keyword ? v.name.replace(keyword, `<span style="color:red;">${keyword}</span>`) : v.name 
                  }}></span>
                  {getCityNum(v.id)}
                </span>
              </span>
            </span>
          ))}
        </div>
      );
    } else {
      return (
        <div style={{ height: "250px" }}>
          <Empty description="请选择省份" />
        </div>
      );
    }
  };

  //渲染区域列表
  const renderArea = () => {
    if (cityId) {
      const arr = find(data, ["id", provinceId])?.childs;
      const arr1 = find(arr, ["id", cityId])?.childs;
      return (
        <div style={{ flex: 1, lineHeight: "32px", overflow: "auto" }}>
          {arr1?.map(v => (
            <span key={v.id} style={{ margin: "0 8px" }}>
              <Checkbox checked={getAreaChecked(v.id)} onClick={e => handleSelectArea(e, v.id)}>
                 <span dangerouslySetInnerHTML={{ 
                  __html: keyword ? v.name.replace(keyword, `<span style="color:red;">${keyword}</span>`) : v.name 
                  }}></span>
              </Checkbox>
            </span>
          ))}
        </div>
      );
    } else {
      return (
        <div>
          <Empty description="请选择市" />
        </div>
      );
    }
  };

  //计算该省份选择市的数量
  const getProvinceNum = id => {
    const obj = find(selectData, ["id", id]);
    if (obj) {
      return `（${obj.childs.length}）`;
    }
    return `（0）`;
  };

  //计算该城市选择区的数量
  const getCityNum = id => {
    const obj = find(selectData, ["id", provinceId]);
    if (obj) {
      const obj1 = find(obj.childs, ["id", id]);
      if (obj1) {
        return `（${obj1.childs.length}）`;
      }
      return `（0）`;
    }
    return `（0）`;
  };

  //显示是否全选
  const handleSelectAll = id => {
    let num2 = find(selectData, ["id", id]) ? find(selectData, ["id", id]).childs.length : undefined;
    if (num2) {
      let num1 = find(data, ["id", id]).childs.length;
      if (num2 < num1) {
        return true;
      }
      return false;
    }
    return false;
  };

  //删除常用地址
  const deleteCommonAddress = async (e, configId) => {
    e.stopPropagation();
    setLoading(true);
    const { success, msg } = await delQuickSearchOp({ configId });
    if (success) {
    	message.success(msg);
    	getCommonAddressList();
    }
    setLoading(false);
  };

  //选择常用地址
  const selectCommonAddress = val => {
    const addressList = val.param ? JSON.parse(val.param) : [];
    setProvinceId(addressList[0]?.id);
    setCityId(addressList[0]?.childs[0]?.id);
    setSelectData(addressList);
  };

  const onOk = () => {
    if (selectData.length > 0) {
      const arr = [];
      selectData.forEach(item => {
        item.childs.forEach(it => {
          it.childs.forEach(e => {
            arr.push(e.id);
          });
        });
      });
      handleOk(arr, selectData);
    } else {
      handleOk(undefined, []);
    }
    setOpen(false);
  };

  //添加常用地址命名弹窗
  const AddCommonAddressProps = {
    page,
    selectData,
    items: commonAddressList,
    handleCancel() {
      setAddVisible(false);
    },
    handleOk() {
      getCommonAddressList();
      setAddVisible(false);
    }
  };

  function filterFunc(treeData, str) {
    return treeData.filter(node => {
      // 判断当前节点的名字是否包含关键字
      if (node.name.includes(str)) {
        return true;
      }

      // 递归过滤子节点
      if (node.childs && node.childs.length > 0) {
        node.childs = filterFunc(node.childs, str);
        return node.childs.length > 0;
      }

      return false;
    });
  }

  const handleFilterArea = (val) => {
    const keyword = val.keyword?.replaceAll(" ", '');
    selectData?.length && setSelectData([]);
    if(keyword){
      setKeyword(keyword);
      const newTree = filterFunc(cloneDeep(allData), keyword);
      setData(newTree);
      const temp = newTree?.[0];
    if (temp) {
      setProvinceId(temp?.id);
      setCityId(temp?.childs?.[0]?.id);
    }
    }else{
      message.info('输入内容为空');
    }
  }

  const onReset = () => {
    form.resetFields();
    setData(allData);
    keyword && setKeyword('');
    selectData?.length && setSelectData([]);
    const temp = allData?.[0];
    if (temp) {
      setProvinceId(temp?.id);
      setCityId(temp?.childs?.[0]?.id);
    }
  }

  return <CommonModal
    title="请选择省市区"
    visible={open}
    width={980}
    onCancel={() => setOpen(false)}
    afterClose={handleCancel}
    footer={[<Button key='save' disabled={commonAddressList?.length >= 20 || !selectData?.length} onClick={()=>setAddVisible(true)}>保存为常用地址({commonAddressList?.length}/20)</Button>,
    <Button key='cancel' onClick={() => setOpen(false)}>取消</Button>,
    <Button key='ok' type='primary' onClick={onOk}>确定</Button>
    ]}
  >
    <Form form={form} onFinish={handleFilterArea} layout='inline'>
      <Form.Item name='keyword' label="省市区">
        <Input placeholder='请输入' style={{width:"520px"}}/>
      </Form.Item>
      <Form.Item>
        <Button
          type="primary"
          // icon={<IconFont type="iconsousuo" style={{ fontSize: 14 }} />}
          htmlType="submit"
          style={{ marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={onReset} className="mb16 ml8" style={{ order: 181 }}>重置</Button>
      </Form.Item>
    </Form>
    <div className="flex">
      <div style={{ width: "380px", overflow: "auto" }}>
        <h3 style={{ marginBottom: "8px" }}>省列表：</h3>
        <div style={{ display: "flex", flexWrap: "wrap" }}>
          {data.map(v => (
            <div key={v.id} className="flex-row-center" style={{ width: "112px", margin: "2px 4px" }}>
              <Checkbox
                indeterminate={handleSelectAll(v.id)}
                checked={getProvinceChecked(v.id)}
                onChange={e => handleSelectProvince(e, v.id)}
              />
              <span
                className={v.id == provinceId ? "common-color2" : "common-color4 common-color2"}
                style={{ marginLeft: 8 }}
                onClick={() => handleClickProvince(v.id)}
                key={v.id}
              >
                <span dangerouslySetInnerHTML={{ 
                  __html: keyword ? v.name.replace(keyword, `<span style="color:red;">${keyword}</span>`) : v.name 
                  }}></span>
                {getProvinceNum(v.id)}
              </span>
            </div>
          ))}
        </div>
      </div>
      <Divider type="vertical" style={{ height: "345px" }} />
      <div className="flex" style={{ flex: 1 }}>
        <div>
          <h3 style={{ marginBottom: "8px" }}>市列表：</h3>
          {renderCity()}
        </div>
        <Divider type="vertical" style={{ height: "345px" }} />
        <div>
          <h3>区列表：</h3>
          {renderArea()}
        </div>
      </div>
    </div>
    <div>
      {
        commonAddressList.map(item=>{
          return (
            <div
              key={item.id}
              className={styles.search_tag}
              onClick={() => selectCommonAddress(item)}
            >
              {item.name}
              <Popconfirm
                title="确定删除该常用地址吗?"
                onConfirm={e => deleteCommonAddress(e, item.id)}
                okText="确定"
                cancelText="取消"
              >
              <CloseOutlined className={styles.search_tag_close} onClick={e=>e.stopPropagation()}/>
              </Popconfirm>
            </div>
          );
        })
      }
    </div>
   { addVisible && <NamedAddressModal {...AddCommonAddressProps} />}
   <CommonLoading loading={loading} />
  </CommonModal>
}